#include<stdio.h>
#include<stdlib.h>
typedef int SLDataType;
typedef struct SeqList{
  SLDataType*a;
  int size;
  int capacity;	
}SL;
void SeqListPrint(SL*ps){
	printf("seqlist:");
	for(int i=0;i<ps->size;i++){
		printf("%d ",ps->a[i]);
	}
	printf("\n");
}
void SeqListDestory(SL*ps){
	free(ps->a);
	ps->a=NULL;
	ps->size=ps->capacity=0;
}
void SeqListInit(SL*ps){
	ps->a=NULL;
	ps->size=ps->capacity=0;
}
void SeqListcheckcapacity(SL*ps){
	if(ps->size==ps->capacity){
		int newcapacity=ps->capacity==0?4:ps->capacity*2;
	    SLDataType*tmp=(SLDataType*)realloc(ps->a,newcapacity*sizeof(SLDataType));
	    if(tmp==NULL){
	    	printf("realloc failed\n");
	    	exit(-1);
		}
		ps->a=tmp;
		ps->capacity=newcapacity;
	} 
} 
void SeqListinsert(SL*ps,int pos,int val){
if(pos<=ps->size&&pos>=0){
	SeqListcheckcapacity(ps);
	for(int end=ps->size-1;end>=pos;end--){
		ps->a[end+1]=ps->a[end];
	}
	ps->a[pos]=val;
	ps->size++;
}
}
void SeqListErase(SL*ps,int pos){
	if(pos<ps->size&&pos>=0){
		int begin=pos;
		while(begin<ps->size-1){
			ps->a[begin]=ps->a[begin+1];
			begin++;
		}
		ps->size--;
	}
	
} 

void SeqListPushBack(SL*ps,SLDataType x){//尾插 
//	SeqListcheckcapacity(ps);
//	ps->a[ps->size]=x;
//	ps->size++;
SeqListinsert(ps,ps->size,x);
}
void SeqListPopBack(SL*ps){//尾删 
//	if(ps->size>0){
//		ps->size--;
//	}
SeqListErase(ps,ps->size-1);
}
void SeqListPushFront(SL*ps,SLDataType x){//头插 
//	SeqListcheckcapacity(ps);
//	int end=ps->size-1;
//	while(end>=0){
//		ps->a[end+1]=ps->a[end];
//		end--;
//	}
//	ps->a[0]=x;
//	ps->size++;
SeqListinsert(ps,0,x);
}
void SeqListPopFront(SL*ps){
//	if(ps->size>0){
//		int begin=1;
//		while(begin<ps->size){
//			ps->a[begin-1]=ps->a[begin];
//			begin++;
//		}
//		ps->size--;
//	}
SeqListErase(ps,0);
} 
int SeqListFind(SL*ps,SLDataType x){
	for(int i=0;i<ps->size;i++){
		if(ps->a[i]==x){
			return i;
		}
	}
	return -1;
}

int main(){
	SL sl;
	SeqListInit(&sl);
	SeqListPushBack(&sl,1);
	SeqListPushBack(&sl,2);
	SeqListPushBack(&sl,3);
	SeqListPushBack(&sl,4);
	SeqListPushBack(&sl,5);
	SeqListPushBack(&sl,4);
	SeqListPushBack(&sl,5);
	SeqListPrint(&sl);
	
	SeqListPopBack(&sl);
	SeqListPopBack(&sl);
	SeqListPopBack(&sl);
	SeqListPopBack(&sl);	
	SeqListPrint(&sl);
	
	SeqListPushBack(&sl,1);
	SeqListPushBack(&sl,2);
	SeqListPushBack(&sl,3);
	SeqListPrint(&sl);
	
	SeqListPushFront(&sl,7);
	SeqListPushFront(&sl,7);
	SeqListPrint(&sl);
	
	SeqListPopFront(&sl);
	SeqListPopFront(&sl);
	SeqListPrint(&sl);
	int x=5; 
	printf("所查找元素%d的下标是：%d（-1表不存在）\n",x,SeqListFind(&sl,x));
	SeqListinsert(&sl,6,5);
	printf("往下标%d 位置插入%d后的顺序表是：",6,5);
	SeqListPrint(&sl); 
	
	SeqListErase(&sl,3);
	SeqListErase(&sl,4);
	SeqListPrint(&sl);
	return 0;
} 
